/**
 * Notes: 研发项目模块控制器
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2023-08-30 19:20:00
 */

const BaseProjectController = require('./base_project_controller.js');
const ResearchProjectService = require('../service/research_project_service.js');
const timeUtil = require('../../../framework/helpers/time_util.js');
const contentCheck = require('../../../framework/validate/content_check.js');
const appCode = require('../../../framework/core/app_code.js');
const InitCloudCollections = require('../init/init_cloud_collections.js');
const AppError = require('../../../framework/core/app_error.js');

class ResearchProjectController extends BaseProjectController {

	/** 构造函数 */
	constructor(route, openId, event) {
		super(route, openId, event);
		this._service = new ResearchProjectService();
		this._dbInitialized = false;
	}
	
	/**
	 * 初始化设置
	 */
	async initSetup() {
		console.log('[PLM-ResearchProjectController] initSetup called');
		
		// 确保数据库集合已初始化
		try {
			console.log('[PLM-ResearchProjectController] 初始化数据库集合...');
			// 导入init模块
			const InitCloudCollections = require('../init/init_cloud_collections.js');
			const initResult = await InitCloudCollections.initCollections();
			console.log('[PLM-ResearchProjectController] 数据库初始化结果:', initResult);
			
			// 从结果中提取集合状态
			if (initResult.code === 0) {
				console.log('[PLM-ResearchProjectController] 数据库初始化成功');
			} else {
				console.warn('[PLM-ResearchProjectController] 数据库初始化可能存在问题: ' + initResult.message);
			}
		} catch (error) {
			console.error('[PLM-ResearchProjectController] 数据库初始化失败:', error);
			// 继续执行，不阻断请求
		}
		
		return true;
	}

	/**
	 * 创建研发项目
	 * @param {*} event 
	 * @param {*} user 
	 */
	async createProject(event, user) {
		console.log('[createProject] 开始创建项目...');
		
		try {
			// 获取原始事件数据
			const rawEvent = this._event;
			console.log('[createProject] 原始事件数据:', JSON.stringify(rawEvent).substring(0, 300) + '...');
			
			// 直接从原始事件中提取params
			let input = null;
			
			if (rawEvent && rawEvent.params) {
				input = rawEvent.params;
				console.log('[createProject] 成功从原始事件params获取数据');
			} else if (event && event.params) {
				input = event.params;
				console.log('[createProject] 从event.params获取数据');
			} else if (event && typeof event === 'object' && Object.keys(event).length > 0) {
				input = event;
				console.log('[createProject] 直接使用event作为输入');
			} else if (this._params) {
				input = this._params;
				console.log('[createProject] 使用this._params作为输入');
			} else {
				throw new Error('无法获取项目参数');
			}
			
			// 确保input存在
			if (!input || typeof input !== 'object') {
				throw new Error('无效的项目参数');
			}
			
			console.log('[createProject] 输入数据:', JSON.stringify(input).substring(0, 300) + '...');
			
			// 安全地获取用户ID
			let userId = "";
			if (user && user._id) {
				userId = user._id;
			} else if (this._userId) {
				userId = this._userId;
			} else {
				// 如果无法获取用户ID，使用默认值
				userId = "system";
				console.log('[createProject] 未找到用户ID，使用默认值:', userId);
			}
			
			// 将输入转换为项目数据对象
			let projectData = {
				...input,
				status: input.status || 'planning', // 默认状态为planning
				applicantId: userId, // 申请者ID
				applicantName: input.applicantName || user?.name || '系统创建', // 申请者名称
				createTime: this._timestamp, // 创建时间
			};
			
			console.log('[createProject] 将要创建的项目数据:', JSON.stringify(projectData).substring(0, 300) + '...');
			
			// 调用服务层创建项目
			let service = new ResearchProjectService();
			let result = await service.createProject(projectData);
			
			console.log('[createProject] 创建项目结果:', result);
			
			return result;
		} catch (err) {
			console.error('[createProject] 创建项目出错:', err);
			throw new AppError('创建项目失败:' + err.message, 500);
		}
	}

	/**
	 * 获取项目列表
	 * @param {*} event 
	 * @param {*} user 
	 * @returns 
	 */
	async getProjectList(event, user) {
		console.log('[getProjectList] 开始获取项目列表...');
		
		let rules = {
			search: 'string|min:1|max:30|name=搜索条件',
			sortType: 'string|name=排序类型',
			sortVal: 'name=排序值',
			status: 'string|name=状态',
			page: 'must|int|default=1',
			size: 'must|int|default=20',
			isTotal: 'string',
			oldTotal: 'int',
		};

		// 取得数据
		let input = this.validateData(event, rules);
		
		let result = await this._service.getProjectList(input);
		
		// 数据格式化
		if (result.list && Array.isArray(result.list)) {
			result.list.forEach(item => {
				if (item.startDate) 
					item.startDateFormatted = timeUtil.timestamp2Time(item.startDate, 'Y-M-D');
				
				if (item.deadline) 
					item.deadlineFormatted = timeUtil.timestamp2Time(item.deadline, 'Y-M-D');
				
				if (item.planStartDate) 
					item.planStartDateFormatted = timeUtil.timestamp2Time(item.planStartDate, 'Y-M-D');
				
				if (item.planEndDate) 
					item.planEndDateFormatted = timeUtil.timestamp2Time(item.planEndDate, 'Y-M-D');
                
                if (item.createTime)
                    item.createTimeFormatted = timeUtil.timestamp2Time(item.createTime, 'Y-M-D h:m');
                
                if (item.updateTime)
                    item.updateTimeFormatted = timeUtil.timestamp2Time(item.updateTime, 'Y-M-D h:m');
                
                if (item.stateTime)
                    item.stateTimeFormatted = timeUtil.timestamp2Time(item.stateTime, 'Y-M-D h:m');
                
                // 删除旧字段
                const oldFields = ['id', 'projectTitle', 'statusDesc', 'startDateStr', 'deadlineStr', 
                                  'planStartDateStr', 'planEndDateStr', 'createTimeStr', 'updateTimeStr', 'stateTimeStr'];
                
                oldFields.forEach(field => {
                    if (item[field]) {
                        delete item[field];
                    }
                });
			});
		}
		
		return result;
	}

	/**
	 * 获取项目详情
	 * @param {*} event 
	 * @param {*} user 
	 * @returns 
	 */
	async getProjectDetail(event, user) {
		console.log('[getProjectDetail] 开始获取项目详情...');
		
		let rules = {
			id: 'required|id|name=项目ID',
		};

		// 取得数据
		let input = this.validateData(event, rules);
		
		let project = await this._service.getProjectById(input.id);
		
		if (!project) {
			return appCode.PROJECT_NOT_FOUND;
		}
		
		// 格式化日期
		if (project.startDate) 
			project.startDateFormatted = timeUtil.timestamp2Time(project.startDate, 'Y-M-D');
		
		if (project.deadline) 
			project.deadlineFormatted = timeUtil.timestamp2Time(project.deadline, 'Y-M-D');
		
		if (project.planStartDate) 
			project.planStartDateFormatted = timeUtil.timestamp2Time(project.planStartDate, 'Y-M-D');
		
		if (project.planEndDate) 
			project.planEndDateFormatted = timeUtil.timestamp2Time(project.planEndDate, 'Y-M-D');
        
        if (project.createTime)
            project.createTimeFormatted = timeUtil.timestamp2Time(project.createTime, 'Y-M-D h:m');
        
        if (project.updateTime)
            project.updateTimeFormatted = timeUtil.timestamp2Time(project.updateTime, 'Y-M-D h:m');
        
        if (project.stateTime)
            project.stateTimeFormatted = timeUtil.timestamp2Time(project.stateTime, 'Y-M-D h:m');
        
        // 移除旧字段
        const oldFields = ['id', 'projectTitle', 'statusDesc', 'startDateStr', 'deadlineStr', 
                           'planStartDateStr', 'planEndDateStr', 'createTimeStr', 'updateTimeStr', 'stateTimeStr'];
        
        oldFields.forEach(field => {
            if (project[field]) {
                delete project[field];
            }
        });
		
		return project;
	}

	/**
	 * 更新项目
	 * @param {*} event 
	 * @param {*} user 
	 * @returns 
	 */
	async updateProject(event, user) {
		console.log('[updateProject] 开始更新项目...');
		
		let rules = {
			id: 'required|id|name=项目ID',
			projectType: 'required|string|min:2|max:100|name=项目类型',
			customerName: 'required|string|min:2|max:50|name=客户名称',
			// 移除applicationType
			// applicationType: 'required|string|min:2|max:50|name=应用类型',
			description: 'string|max:50000|name=项目描述',
			
			// 时间相关
			startDate: 'required|date|name=开始日期',
			deadline: 'required|date|name=截止日期',
			planStartDate: 'date|name=计划开始日期',
			planEndDate: 'date|name=计划结束日期',
			
			// 优先级
			priority: 'required|string|in:low,normal,high,urgent|name=优先级',
            
			// 样机相关
			hasSample: 'string|name=有无样机',
			sampleCount: 'string|name=样机数量',
			sampleImages: 'array|name=样机图片',
            
			// 电机控制相关
			workTemp: 'string|name=工作环境温度',
			certification: 'string|name=认证要求',
			lowPower: 'string|name=低功耗要求',
			startupTime: 'string|name=启动时间要求',
			conformalCoating: 'string|name=三防漆要求',
			
			// 电机参数
			ratedVoltage: 'string|name=额定电压',
			maxPower: 'string|name=最大功率',
			maxSpeed: 'string|name=最高转速',
			polePairs: 'string|name=极对数',
			hasHall: 'string|name=HALL/磁编',
			hasFG: 'string|name=FG信号',
			hasBrake: 'string|name=刹车功能',
			
			// 控制参数
			controlMode: 'string|name=控制模式',
			controlAlgorithm: 'string|name=控制算法',
			rotation: 'string|name=正反转方式',
			controlInterface: 'string|name=控制接口',
			
			// 保护参数
			stallProtection: 'string|name=堵转保护',
			overvoltageProtection: 'string|name=过压保护',
			undervoltageProtection: 'string|name=欠压保护',
			temperatureProtection: 'string|name=温度保护',
			overcurrentProtection: 'string|name=过流保护',
			currentLimitProtection: 'string|name=限流保护',
			blockageProtection: 'string|name=堵孔/空转保护',
			phaseProtection: 'string|name=缺相保护'
		};

		// 取得数据
		let input = this.validateData(event, rules);
		
		// 移除不需要的字段
		if (input.applicationType) {
		    delete input.applicationType;
		}
		if (input.projectTypeName) {
		    delete input.projectTypeName;
		}
		if (input.projectTitle) {
		    delete input.projectTitle;
		}
		
		// 内容校验
		await contentCheck.checkTextMultiClient(input);
		
		// 获取原项目信息进行比对
		let oldProject = await this._service.getProjectById(input.id);
		if (!oldProject) {
			return appCode.PROJECT_NOT_FOUND;
		}
		
		// 时间格式转换
		input.startDate = timeUtil.time2Timestamp(input.startDate);
		input.deadline = timeUtil.time2Timestamp(input.deadline);
		input.planStartDate = timeUtil.time2Timestamp(input.planStartDate);
		input.planEndDate = timeUtil.time2Timestamp(input.planEndDate);
		
		// 执行更新
		await this._service.updateProject(input.id, input);
		
		return { _id: input.id };
	}

	/**
	 * 测试方法 - 查询最新创建的项目数据
	 * @param {*} event 
	 * @param {*} user 
	 * @returns 
	 */
	async testQueryLatest(event, user) {
		console.log('[testQueryLatest] 开始测试查询...');
		
		try {
			// 获取云开发实例
			const cloudBase = require('../../../framework/cloud/cloud_base.js');
			const cloud = cloudBase.getCloud();
			const db = cloud.database();
			
			// 集合名称
			const collectionName = 'plm_research_project';
			console.log(`[testQueryLatest] 尝试查询集合: ${collectionName}`);
			
			// 获取总记录数
			const countResult = await db.collection(collectionName).count();
			console.log(`[testQueryLatest] 集合总记录数: ${countResult.total}`);
			
			// 查询最新记录
			const result = await db.collection(collectionName)
				.limit(1)
				.get();
			
			if (result && result.data && result.data.length > 0) {
				const record = result.data[0];
				console.log('[testQueryLatest] 找到最新记录:');
				console.log('记录ID:', record._id);
				console.log('字段数量:', Object.keys(record).length);
				console.log('字段列表:', Object.keys(record).join(', '));
				
				// 返回测试结果
				return {
					code: 0,
					data: {
						recordId: record._id,
						fieldCount: Object.keys(record).length,
						fieldList: Object.keys(record),
						record: record
					}
				};
			} else {
				console.log('[testQueryLatest] 未找到记录');
				return { code: -1, message: '未找到记录' };
			}
		} catch (err) {
			console.error('[testQueryLatest] 查询出错:', err);
			return { code: -1, error: err.message };
		}
	}
}

module.exports = ResearchProjectController; 